package com.yangrd.helper.crudhelper.core.crud.page.impl;

import com.yangrd.helper.crudhelper.core.crud.page.CrudPage;
import com.yangrd.helper.crudhelper.core.crud.page.CrudPageFactory;
import com.yangrd.helper.crudhelper.core.crud.page.CrudPageInitService;
import com.yangrd.helper.crudhelper.core.crud.page.CrudPageRepository;
import lombok.RequiredArgsConstructor;

import javax.annotation.PreDestroy;
import java.util.Collection;

/**
 * description: SimpleCrudPageInitService
 *
 * @author: yangrd
 * @date: 2020/10/23
 * @version: 1.0
 */
@RequiredArgsConstructor
public class SimpleCrudPageInitService implements CrudPageInitService {

    private final CrudPageFactory crudPageFactory;

    private final CrudPageRepository crudPageRepository;

    private Collection<Class<?>> classCollection;

    @Override
    public void init(Collection<Class<?>> classCollection) {
        this.classCollection = classCollection;
        if (crudPageRepository.get(classCollection.iterator().next()).isPresent()) {
            return;
        }
        classCollection.forEach(this::refresh);
    }

    @Override
    public void refresh(Class<?> domainClass) {
        CrudPage crudPage = crudPageFactory.create(domainClass);
        crudPageRepository.put(domainClass, crudPage);
    }

    @Override
    public void refreshAll() {
        this.classCollection.forEach(this::refresh);
    }

    @PreDestroy
    @Override
    public void destroy() {
        classCollection.clear();
    }
}
